'use strict'

module.exports = angular.module 'services.account', [
  require 'angular-resource'
  require('baseService').name
  require('sessionService').name
]
.factory "AccountService", ($log, $resource, $q, Constant, BaseService, SessionService)->
  $log.log "account service init"
  class AccountService

    constructor: ->
      @baseService = new BaseService()
      constant = new Constant()
      @operationDomain = constant.OPERATION_DOMAIN
      @openMsgService = $resource "#{@operationDomain}/passport/ops/openId"
      @logoutService  = $resource "#{@operationDomain}/passport/union/logout", null, {post: {method: 'POST'}}
      @permissionService  = $resource "#{@operationDomain}/passport/operator/:operatorUuid/permission"

    getOpenMsg: (successCb, errorCb)->
      return if !successCb
      promise = @openMsgService.get( platform: 'WEB' ).$promise
      @baseService.deal promise, successCb, errorCb

    getPermissions: (params, successCb, errorCb)->
      return if !successCb
      params.systemCode = 'COMMON'
      promise = @permissionService.query( params ).$promise
      @baseService.deal promise, successCb, errorCb

    logout: (successCb, errorCb)->
      return if !successCb
      promise = @logoutService.post().$promise
      @baseService.deal promise, successCb, errorCb

    get: (successCb, errorCb)->
      return if !successCb
      sessionService = new SessionService()
      headers = {}
      headers["#{sessionService.TOKEN}"] = sessionService.getToken()
      $.ajax
        url: "#{@operationDomain}/passport/union/auth"
        async: false
        method: "GET"
        headers: headers
        success: (user)->
          successCb user
        error: (err)->
          errorCb err if errorCb?

    getPermissionSync: (params, successCb, errorCb)->
      return if !successCb
      sessionService = new SessionService()
      headers = {}
      headers["#{sessionService.TOKEN}"] = sessionService.getToken()
      $.ajax
        url: "#{@operationDomain}/passport/operator/#{params.operatorUuid}/permission"
        async: false
        method: "GET"
        headers: headers
        success: (user)->
          successCb user
        error: (err)->
          errorCb err if errorCb?

# 用户是否已登录
    isAuthenticated: (successCb, errorCb)->
      @get (user)->
        successCb user if successCb?
      , (error)->
        errorCb error if errorCb?
